FIND_PACKAGE (Perl)

EXECUTE_PROCESS(COMMAND ${PERL_EXECUTABLE} -e "use Config; print \$Config{ccflags}" OUTPUT_VARIABLE PERL_CCFLAGS)
EXECUTE_PROCESS(COMMAND ${PERL_EXECUTABLE} -e "use Config; print \$Config{archlib}.\"/CORE\"" OUTPUT_VARIABLE PERL_CORE_DIR)
EXECUTE_PROCESS(COMMAND ${PERL_EXECUTABLE} -e "use Config; print \$Config{ccldflags}" OUTPUT_VARIABLE PERL_CCLDFLAGS)
EXECUTE_PROCESS(COMMAND ${PERL_EXECUTABLE} -e "use Config; print \$Config{installsitearch}" OUTPUT_VARIABLE PERL_SITEARCHDIR)
EXECUTE_PROCESS(COMMAND ${PERL_EXECUTABLE} -e "use Config; print \$Config{installvendorarch}" OUTPUT_VARIABLE PERL_VENDORARCHDIR)

IF (USE_VENDORDIRS)
    SET (PERL_INSTALL_DIR ${PERL_VENDORARCHDIR})
ELSE (USE_VENDORDIRS)
    SET (PERL_INSTALL_DIR ${PERL_SITEARCHDIR})
ENDIF (USE_VENDORDIRS)

MESSAGE (STATUS "Perl executable: ${PERL_EXECUTABLE}")
MESSAGE (STATUS "Perl installation dir: ${PERL_INSTALL_DIR}")

ADD_CUSTOM_COMMAND (
    OUTPUT solv_perl.c
    COMMAND ${SWIG_EXECUTABLE} -perl ${SWIG_FLAGS} -I${CMAKE_SOURCE_DIR}/src -o solv_perl.c ${CMAKE_SOURCE_DIR}/bindings/solv.i
    COMMAND sed -i -e "s/SvTYPE(tsv) == SVt_PVHV/SvTYPE(tsv) == SVt_PVHV || SvTYPE(tsv) == SVt_PVAV/" solv_perl.c
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    DEPENDS ${CMAKE_SOURCE_DIR}/bindings/solv.i
    VERBATIM
)

ADD_DEFINITIONS(${PERL_CCFLAGS} -Wno-unused -Wno-nonnull)
LINK_DIRECTORIES (${PERL_CORE_DIR})
INCLUDE_DIRECTORIES (${PERL_INCLUDE_PATH} ${PERL_CORE_DIR})

ADD_LIBRARY (bindings_perl MODULE solv_perl.c)
SET_TARGET_PROPERTIES (bindings_perl PROPERTIES PREFIX "" OUTPUT_NAME "solv")
SET_TARGET_PROPERTIES (bindings_perl PROPERTIES LINK_FLAGS "${PERL_CCLDFLAGS}")
TARGET_LINK_LIBRARIES (bindings_perl libsolvext libsolv ${SYSTEM_LIBRARIES})

INSTALL (TARGETS bindings_perl LIBRARY DESTINATION ${PERL_INSTALL_DIR})
INSTALL (FILES ${CMAKE_CURRENT_BINARY_DIR}/solv.pm DESTINATION ${PERL_INSTALL_DIR})
